<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>
          <a-col :xl='24' :lg='7' :md='8' :sm='24'>
            <a-radio-group v-model='queryParam.stageLabelStatus' @change='radioChange'>
              <a-form-item label='商机阶段'>
                <a-radio :value='0'>正常(0%-90%)</a-radio>
                <a-radio :value='1'>中标(100%)</a-radio>
                <a-radio :value='2'>关闭</a-radio>
                <a-radio :value='3'>全部</a-radio>
              </a-form-item>
            </a-radio-group>
          </a-col>
        </a-row>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='商机名称'>
              <a-input placeholder='请输入商机名称' v-model='queryParam.name'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='销售经理'>
              <a-input placeholder='请输入销售经理' v-model='queryParam.saleLeader'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='售前经理'>
              <a-input placeholder='请输入售前经理' v-model='queryParam.preSaleLeader'></a-input>
            </a-form-item>
          </a-col>
          <template v-if='toggleSearchStatus'>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='客户简称'>
                <a-input placeholder='请输入客户简称' v-model='queryParam.shortName'></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='产品类型'>
                <j-dict-select-tag
                  placeholder='请选择产品类型'
                  v-model='queryParam.type'
                  dictCode='icm_bus_business_opportunity_type'
                />
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='7' :md='8' :sm='24'>
              <a-form-item label='商机阶段'>
                <j-dict-select-tag
                  v-model='queryParam.stagePlannedSpeed'
                  placeholder='请选择阶段'
                  dictCode='hf_bus_opportunity_stage,label,planned_speed'
                />
              </a-form-item>
            </a-col>
            <a-col :xl='6' :lg='6' :md='8' :sm='12'>
              <a-form-item label='预计签单时间'>
                <j-date
                  placeholder='请选择开始日期'
                  class='query-group-cust'
                  v-model='queryParam.expectSignTime_begin'
                ></j-date>
                <span class='query-group-split-cust'></span>
                <j-date
                  placeholder='请选择结束日期'
                  class='query-group-cust'
                  v-model='queryParam.expectSignTime_end'
                ></j-date>
              </a-form-item>
            </a-col>

            <a-col :xl='6' :lg='6' :md='8' :sm='12'>
              <a-form-item label='创建时间'>
                <j-date
                  placeholder='请选择开始日期'
                  class='query-group-cust'
                  v-model='queryParam.createTime_begin'
                ></j-date>
                <span class='query-group-split-cust'></span>
                <j-date
                  placeholder='请选择结束日期'
                  class='query-group-cust'
                  v-model='queryParam.createTime_end'
                ></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left; overflow: hidden' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
              <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='handleAdd' type='primary' icon='plus'>新增</a-button>
      <a-button
        type='primary'
        icon='download'
        @click="handleExportXls('客户商机')"
        v-has="'BusBusinessOpportunity:export'"
      >
        导出
      </a-button>
      <!--      <a-upload name='file' :showUploadList='false' :multiple='false' :headers='tokenHeader' :action='importExcelUrl'-->
      <!--                @change='handleImportExcel'>-->
      <!--        <a-button type='primary' icon='import'>导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList='superFieldList' ref='superQueryModal'-->
      <!--                     @handleSuperQuery='handleSuperQuery'></j-super-query>-->
      <!--      <a-dropdown v-if='selectedRowKeys.length > 0'>-->
      <!--        <a-menu slot='overlay'>-->
      <!--          <a-menu-item key='1' @click='afterBatchDel'>-->
      <!--            <a-icon type='delete' />-->
      <!--            删除-->
      <!--          </a-menu-item>-->
      <!--        </a-menu>-->
      <!--        <a-button style='margin-left: 8px'> 批量操作-->
      <!--          <a-icon type='down' />-->
      <!--        </a-button>-->
      <!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择
        <a style='font-weight: 600'>{{ selectedRowKeys.length }}</a
        >项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        :scroll='{ x: true }'
        bordered
        rowKey='id'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :loading='loading'
        :rowClassName='changeClassName'
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
        class='j-table-force-nowrap'
        @change='handleTableChange'
      >
        <template slot='num' slot-scope='text, record'>
          <a @click='handleDetail(record)'>{{ text }}</a>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px; font-style: italic'>无图片</span>
          <img
            v-else
            :src='getImgView(text)'
            height='25px'
            alt=''
            style='max-width: 80px; font-size: 12px; font-style: italic'
          />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px; font-style: italic'>无文件</span>
          <a-button v-else :ghost='true' type='primary' icon='download' size='small' @click='downloadFile(text)'>
            下载
          </a-button>
        </template>

        <div slot='action' slot-scope='text, record' v-has="'BusBusinessOpportunity:edit'">
          <a @click='handleEdit(record)' v-if="record.stageStatistics == 'Y'">编辑</a>
          <a-divider type='vertical' v-if="record.stageStatistics == 'Y'" />
          <a-dropdown>
            <a class='ant-dropdown-link' v-if="record.stageStatistics == 'Y'">更多
              <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <!-- <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item> -->
              <a-menu-item>
                <a-popconfirm title='确定删除吗?' @confirm='() => afterHandleDelete(record.id)'>
                  <a style='color:red'>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          <a-divider type='vertical'  v-if="record.stageStatistics == 'Y'"/>
          <a-dropdown>
            <a class='ant-dropdown-link'>附加
              <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a @click='saleActivityHandleEdit(record)'>销售活动</a>
              </a-menu-item>
              <a-menu-item>
                <a @click='salebeforeApplyHandleEdit(record)'>售前申请</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
        <!-- <span slot="fictitiousQuota" slot-scope="text, record">
          {{ (record.budget * record.stagePlannedSpeed) / 100 }}
        </span>
        <span slot="fictitiousProfit" slot-scope="text, record">
          {{ ((record.grossProfit * record.stagePlannedSpeed) / 100).toFixed(2) }}
        </span> -->
      </a-table>
      <a-row>
        <a-col :span='6'>
          <a-card>
            <a-statistic title='商机预算合计（元）' :value='budgetSum' />
          </a-card>
        </a-col>
        <a-col :span='6'>
          <a-card>
            <a-statistic title='虚拟成交额（元）' :value='fictitiousQuota' />
          </a-card>
        </a-col>
        <a-col :span='6'>
          <a-card>
            <a-statistic title='预计毛利合计（元）' :value='grossProfitSum' />
          </a-card>
        </a-col>
        <a-col :span='6'>
          <a-card>
            <a-statistic title='虚拟毛利（元）' :value='fictitiousProfit' />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <bus-business-opportunity-change-list
      :mainId='selectedMainId'
      :dataType="'BusBusinessOpportunity'"
      ref='updateShow'
    />

    <bus-business-opportunity-modal ref='modalForm' @ok='afterModalFormOk'></bus-business-opportunity-modal>
    <bus-sale-activity-modal ref='saleActivityModalForm' @ok='saleActivityOk'></bus-sale-activity-modal>
    <bus-salebefore-apply-modal ref='salebeforeApplyModalForm' @ok='salebeforeApplyOk'></bus-salebefore-apply-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { sorter } from '@/utils/sorter'
import { loginUserButtonAuth } from '@/utils/loginUserButtonAuth'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import BusBusinessOpportunityModal from './modules/BusBusinessOpportunityModal'
import ContractPurchaseModal from '@views/hifar/contract/modules/ContractPurchaseModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import BusSaleActivityModal from '@views/hifar/business/modules/BusSaleActivityModal'
import BusSalebeforeApplyModal from '@views/hifar/business/modules/BusSalebeforeApplyModal'
import ContractSaleModal from '@views/hifar/contract/modules/ContractSaleModal'
import { deleteAction, getAction, postAction } from '@api/manage'
import pick from 'lodash.pick'
import store from '@/store'
import BusBusinessOpportunityChangeList from '@views/hifar/business/BusBusinessOpportunityChangeList'

export default {
  name: 'BusBusinessOpportunityList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    BusBusinessOpportunityModal,
    ContractPurchaseModal,
    BusSaleActivityModal,
    BusSalebeforeApplyModal,
    ContractSaleModal,
    BusBusinessOpportunityChangeList
  },
  data() {
    return {
      description: '客户商机管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商机编号',
          align: 'center',
          dataIndex: 'num',
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '商机名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '客户简称',
          align: 'center',
          dataIndex: 'shortName'
        },
        {
          title: '销售经理',
          align: 'center',
          dataIndex: 'saleLeader'
        },
        {
          title: '售前经理',
          align: 'center',
          dataIndex: 'preSaleLeader'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          sorter: sorter('createTime')
        },
        {
          title: '修改时间',
          align: 'center',
          dataIndex: 'updateTime',
          sorter: sorter('updateTime')
        },
        {
          title: '产品类型',
          align: 'center',
          dataIndex: 'type_dictText'
        },
        {
          title: '预计签单时间',
          align: 'center',
          dataIndex: 'expectSignTime',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: sorter('expectSignTime')
        },
        {
          title: '商机阶段',
          align: 'center',
          dataIndex: 'stageLabel'
        },
        // {
        //   title: '成单可能性',
        //   align: 'center',
        //   dataIndex: 'signPossibility_dictText'
        // },
        {
          title: '商机预算',
          align: 'right',
          dataIndex: 'budget',
          sorter: sorter('budget'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '虚拟成交额',
          align: 'right',
          dataIndex: 'fictitiousQuota',
          // scopedSlots: { customRender: 'fictitiousQuota' },
          sorter: sorter('fictitiousQuota'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '预计毛利',
          align: 'right',
          dataIndex: 'grossProfit',
          sorter: sorter('grossProfit'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '虚拟毛利',
          align: 'right',
          dataIndex: 'fictitiousProfit',
          // scopedSlots: { customRender: 'fictitiousProfit' },
          sorter: sorter('fictitiousProfit'),
          customRender: (text) => {
            return !text ? '0' : String(text.toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          }
        },
        {
          title: '商机来源',
          align: 'center',
          dataIndex: 'source_dictText'
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/bussiness/busBusinessOpportunity/list',
        sum: '/bussiness/busBusinessOpportunity/sum',
        delete: '/bussiness/busBusinessOpportunity/delete',
        deleteBatch: '/bussiness/busBusinessOpportunity/deleteBatch',
        exportXlsUrl: '/bussiness/busBusinessOpportunity/exportXls',
        importExcelUrl: 'bussiness/busBusinessOpportunity/importExcel'
      },
      dictOptions: {},
      superFieldList: [],
      queryModel: 'like',
      queryParam: {
        stageLabelStatus: 0 //默认合同状态本年度
      },
      budgetSum: 0,
      grossProfitSum: 0,
      fictitiousQuota: 0,
      fictitiousProfit: 0,
      selectedMainId: ''
    }
  },
  created() {
    // this.getSuperFieldList()
    this.getSum()
    //判断是否有编辑权限，如果没有就删除最后一列的操作栏
    loginUserButtonAuth(['BusBusinessOpportunity:edit'], this.columns)
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    handleEdit: function(record) {
      record.isEdit = true
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleDetail: function(record) {
      record.isEdit = true
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '商机详情'
      this.$refs.modalForm.disableSubmit = true
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          let dataSource = res.result.records
          dataSource.forEach((v) => {
            if (v.grossProfit && v.stagePlannedSpeed) {
              v.fictitiousProfit = ((v.grossProfit * v.stagePlannedSpeed) / 100)
            }
            if (v.budget && v.stagePlannedSpeed) {
              v.fictitiousQuota = ((v.budget * v.stagePlannedSpeed) / 100)
            }
          })
          this.dataSource = dataSource
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    handleTableChange(pagination, filters, sorter) {
      if (sorter.field == 'fictitiousProfit') {
        this.dataSource.sort((a, b) => {
          return a.fictitiousProfit - b.fictitiousProfit
        })
      } else if (sorter.field == 'budget') {
        this.dataSource.sort((a, b) => {
          return a.budget - b.budget
        })
      } else if (sorter.field == 'fictitiousQuota') {
        this.dataSource.sort((a, b) => {
          return a.fictitiousQuota - b.fictitiousQuota
        })
      } else if (sorter.field == 'grossProfit') {
        this.dataSource.sort((a, b) => {
          return a.grossProfit - b.grossProfit
        })
      } else {
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        }
      }
      this.ipagination = pagination
      this.loadData()
    },
    changeClassName(record) {
      if (record.updateTime) {
        if (new Date().getTime() - new Date(record.updateTime).getTime() > 2 * 30 * 24 * 60 * 60 * 1000) {
          return 'changeBg'
        }
      }
      return ''
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.id.split(','), [record])
          }
        }
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectedMainId = ''
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedMainId = selectedRowKeys[0]
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    searchQuery() {
      this.onClearSelected()
      this.$refs.updateShow.showChangeTable = false
      this.getSum()
      this.loadData(1)
    },
    searchReset() {
      this.$refs.updateShow.showChangeTable = false
      this.onClearSelected()
      this.queryParam = {}
      this.queryParam.stageLabelStatus = 0
      this.getSum()
      this.loadData(1)
    },
    handleAdd: function() {
      this.$refs.updateShow.showChangeTable = false
      this.onClearSelected()
      let record = {
        saleLeader: store.getters.userInfo.username,
        createTime: new Date().toISOString(),
        stage:'1392424192005283841',
        isEdit: false
      }
      this.$refs.modalForm.addRecord(record)
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    afterBatchDel() {
      this.batchDel()
      this.getSum()
    },
    afterModalFormOk() {
      this.modalFormOk()
      this.getSum()
    },
    afterHandleDelete(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.searchQuery()
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    saleActivityHandleEdit(record) {
      let saleActivity = {
        opportunityId: record.id,
        opportunityName: record.name,
        opportunityNum: record.num,
        saleLeader: record.saleLeader,
        shortName: record.shortName
      }
      this.$refs.saleActivityModalForm.edit(saleActivity)
      this.$refs.saleActivityModalForm.title = '销售活动编辑'
      this.$refs.saleActivityModalForm.disableSubmit = false
    },
    saleActivityOk() {
      this.$router.push('/hifar/business/BusSaleActivityList')
    },
    salebeforeApplyHandleEdit(record) {
      let salebeforeApply = {
        opportunityId: record.id,
        opportunityName: record.name,
        opportunityNum: record.num,
        saleLeader: record.saleLeader,
        createTime: record.createTime,
        shortName: record.shortName
      }
      this.$refs.salebeforeApplyModalForm.edit(salebeforeApply)
      this.$refs.salebeforeApplyModalForm.title = '售前支持审批编辑'
      this.$refs.salebeforeApplyModalForm.disableSubmit = false
    },
    salebeforeApplyOk() {
      this.$router.push('/hifar/business/BusSalebeforeApplyList')
    },
    getSum() {
      var params = this.getQueryParams() //查询条件
      getAction(this.url.sum, params).then((res) => {
        if (res.success) {
          this.budgetSum = res.result.budgetSum.toFixed(2)
          this.grossProfitSum = res.result.grossProfitSum.toFixed(2)
          this.fictitiousQuota = res.result.fictitiousQuota.toFixed(2)
          this.fictitiousProfit = res.result.fictitiousProfit.toFixed(2)
        }
      })
    },
    popupCallback(row) {
      let modal = Object.assign(this.queryParam, row)
      this.queryParam = Object.assign({}, modal)
    },
    radioChange() {
      this.getSum()
      this.loadData()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
.changeBg {
  background: #ffefd5;
}
</style>